package com.supermarket.controller;

import com.supermarket.common.ResponseResult;
import com.supermarket.entity.Address;
import com.supermarket.entity.User;
import com.supermarket.service.AddressService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {
    
    @Resource
    private AddressService addressService;
    
    /**
     * 检查用户权限
     * 
     * @param request HTTP请求
     * @param userId 请求中的用户ID
     * @return 是否有权限
     */
    private ResponseResult<String> checkPermission(HttpServletRequest request, Integer userId) {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        
        if (currentUser == null) {
            return ResponseResult.error(401, "请先登录");
        }
        
        if (!currentUser.getId().equals(userId)) {
            return ResponseResult.error(403, "您无权操作其他用户的地址");
        }
        
        return null; // 返回null表示权限验证通过
    }
    
    /**
     * 添加收货地址
     * 
     * @param address 地址对象
     * @param request HTTP请求
     * @return 操作结果
     */
    @PostMapping("/add")
    public ResponseResult<String> addAddress(@RequestBody Address address, HttpServletRequest request) {
        // 参数校验
        if (address.getUserId() == null) {
            return ResponseResult.error(400, "用户ID不能为空");
        }
        if (address.getReceiverName() == null || address.getReceiverName().trim().isEmpty()) {
            return ResponseResult.error(400, "收货人姓名不能为空");
        }
        if (address.getReceiverPhone() == null || address.getReceiverPhone().trim().isEmpty()) {
            return ResponseResult.error(400, "收货人手机号不能为空");
        }
        if (address.getDetailedAddress() == null || address.getDetailedAddress().trim().isEmpty()) {
            return ResponseResult.error(400, "详细地址不能为空");
        }
        
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, address.getUserId());
        if (permissionCheck != null) {
            return permissionCheck;
        }
        
        int result = addressService.addAddress(address);
        if (result > 0) {
            return ResponseResult.success("添加收货地址成功");
        } else {
            return ResponseResult.error(500, "添加收货地址失败");
        }
    }
    
    /**
     * 更新收货地址
     * 
     * @param address 地址对象
     * @param request HTTP请求
     * @return 操作结果
     */
    @PutMapping("/update")
    public ResponseResult<String> updateAddress(@RequestBody Address address, HttpServletRequest request) {
        // 参数校验
        if (address.getId() == null) {
            return ResponseResult.error(400, "地址ID不能为空");
        }
        if (address.getUserId() == null) {
            return ResponseResult.error(400, "用户ID不能为空");
        }
        
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, address.getUserId());
        if (permissionCheck != null) {
            return permissionCheck;
        }
        
        int result = addressService.updateAddress(address);
        if (result > 0) {
            return ResponseResult.success("更新收货地址成功");
        } else {
            return ResponseResult.error(500, "更新收货地址失败");
        }
    }
    
    /**
     * 删除收货地址
     * 
     * @param id 地址ID
     * @param request HTTP请求
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteAddress(@PathVariable Integer id, HttpServletRequest request) {
        // 获取要删除的地址信息，验证所有权
        Address address = addressService.getAddressById(id);
        if (address == null) {
            return ResponseResult.error(404, "地址不存在");
        }
        
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, address.getUserId());
        if (permissionCheck != null) {
            return permissionCheck;
        }
        
        int result = addressService.deleteAddress(id);
        if (result > 0) {
            return ResponseResult.success("删除收货地址成功");
        } else {
            return ResponseResult.error(500, "删除收货地址失败");
        }
    }
    
    /**
     * 根据ID获取收货地址
     * 
     * @param id 地址ID
     * @param request HTTP请求
     * @return 包含地址信息的响应结果
     */
    @GetMapping("/get/{id}")
    public ResponseResult<Address> getAddressById(@PathVariable Integer id, HttpServletRequest request) {
        Address address = addressService.getAddressById(id);
        if (address == null) {
            return ResponseResult.error(404, "地址不存在");
        }
        
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, address.getUserId());
        if (permissionCheck != null) {
            return ResponseResult.error(permissionCheck.getCode(), permissionCheck.getMessage());
        }
        
        return ResponseResult.success(address);
    }
    
    /**
     * 获取用户的所有收货地址
     * 
     * @param userId 用户ID
     * @param request HTTP请求
     * @return 包含地址列表的响应结果
     */
    @GetMapping("/list")
    public ResponseResult<List<Address>> getAddressByUserId(@RequestParam Integer userId, HttpServletRequest request) {
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, userId);
        if (permissionCheck != null) {
            return ResponseResult.error(permissionCheck.getCode(), permissionCheck.getMessage());
        }
        
        List<Address> addressList = addressService.getAddressByUserId(userId);
        return ResponseResult.success(addressList);
    }
    
    /**
     * 获取用户的默认收货地址
     * 
     * @param userId 用户ID
     * @param request HTTP请求
     * @return 包含默认地址的响应结果
     */
    @GetMapping("/default")
    public ResponseResult<Address> getDefaultAddress(@RequestParam Integer userId, HttpServletRequest request) {
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, userId);
        if (permissionCheck != null) {
            return ResponseResult.error(permissionCheck.getCode(), permissionCheck.getMessage());
        }
        
        Address address = addressService.getDefaultAddressByUserId(userId);
        if (address != null) {
            return ResponseResult.success(address);
        } else {
            return ResponseResult.error(404, "默认地址不存在");
        }
    }
    
    /**
     * 设置默认收货地址
     * 
     * @param id 地址ID
     * @param userId 用户ID
     * @param request HTTP请求
     * @return 操作结果
     */
    @PutMapping("/set-default")
    public ResponseResult<String> setDefaultAddress(@RequestParam Integer id, @RequestParam Integer userId, HttpServletRequest request) {
        // 权限检查
        ResponseResult<String> permissionCheck = checkPermission(request, userId);
        if (permissionCheck != null) {
            return permissionCheck;
        }
        
        int result = addressService.setDefaultAddress(id, userId);
        if (result > 0) {
            return ResponseResult.success("设置默认地址成功");
        } else {
            return ResponseResult.error(500, "设置默认地址失败");
        }
    }
}
